<?php
class ImageAction extends PublicAction {
	
	/**
	 * 跳转到挂图二级页面
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter description here ...
	 */
	public function index() {
		$imageview = D ('ImageView');
		$imagemodel=M('Image');
		$imagelist=$this->category_search($imageview);
		foreach($imagelist as $k => $v)
		{
			$imagelist[$k]['url'] = explode(',', $v['url']);
			$hap['iid']=$v['iid'];
			$imagelist[$k]['desc'] = $imagemodel->where($hap)->getField('desc');
		}
		if(!$imagelist){
			$statusx = 1;
		}else{
			$statusx = 0;
		}
		//获取最近检索词
		$zkeywords=$_SESSION['zkeyword'];
		$this->assign('zkeywords',$zkeywords);
		$this->assign('statusx',$statusx);
		$this->assign ( 'list', $imagelist );
		$this->display ();
	}
	
	public function upload() {
		header('Content-Type:text/html;charset=utf8');
		if (! session ( C ( 'USER_AUTH_KEY' ) ) && ! session ( C ( 'ADMIN_AUTH_KEY' ) )) {
			$this->redirect('User/login');
		}else{
			$uid=getUserInfo('uid');
	   		$basic=M('User')->find($uid); 
	   		if($basic['status'] == 2){
			  	if(session(C("USER_AUTH_KEY")))
				{
					if(session(C("USER_AUTH_KEY"))){
						session(C("USER_AUTH_KEY"),NULL);	
					}
					cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
					cookie(C('USER_AUTH_PWD'),null,-3600);
				}
				$this->redirect('User/login');
	  		 }
			$model = M ( 'Category' );
			$map['status'] = 1;
			$map['catepid'] = 6;
			$list = $model->where ($map)->select ();
			$this->assign ( 'list', $list );
			if ($_GET ['success']) {
				$this->assign ( 'error', $_GET ['error'] );
				$this->assign ( 'val', $_GET ['success'] );
			} else {
				$this->assign ( 'val', 0 );
			}
			$this->display ();
		}
	}
	
	public function imageupload() {
		if (! empty ( $_FILES )) {
			$files = $_FILES;
			$uploadList = uploadsource ( '-1', 'jpg,gif,png,jpeg', './Public/Uploads/Image/', $files, true,'m_,s_','555,140','645,140');
			if (is_array ( $uploadList )) {
				import ( "ORG.Util.Image" );
				//给m_缩略图添加水印, Image::water('原文件名','水印图片地址')
				$num = count ( $uploadList );
				$str = "";
				$size = "";
				$area = "";
				for($i = 0; $i < $num; $i ++) {
					$info = Image::getImageInfo ( $uploadList [$i] ['savepath'] . $uploadList [$i] ['savename'] );
					Image::water ( $uploadList [$i] ['savepath'].'m_'.$uploadList [$i] ['savename'], './Public/Images/logo.jpg', $uploadList [$i] ['savepath'] . 'sy_' . $uploadList [$i] ['savename'], 50 );
					$m = $i + 1;
					if ($info [size] < 1048576) {
						$info [size] = ceil ( $info [size] / 1024 ) . "KB";
					} else {
						$info [size] = round ( ($info [size] / 1048576), 1 ) . "M";
					}
					if ($m < $num) {
						$size .= $info [size] . ",";
						$area .= $info [width] . "×" . $info [height] . ",";
						$str .= $uploadList [$i] ['savename'] . ",";
					} else {
						$size .= $info [size];
						$area .= $info [width] . "×" . $info [height];
						$str .= $uploadList [$i] ['savename'];
					}
				}
				$_POST ['size'] = $size;
				$_POST ['area'] = $area;
				$_POST ['url'] = $str;
			} else {
				$this->error ( $uploadList );
			}
			if (empty ( $_POST ['cateid'] ))
				$_POST ['cateid'] = $_POST ['catepid'];
			$model = D ( 'Image' );
			//保存当前数据对象
			$data = $_POST;
			$data ['size'] = $_POST ['size'];
			$data ['area'] = $_POST ['area'];
			$data ['url'] = $_POST ['url'];
			$data ['uploadtime'] = time();
			if ($model->create ( $data )) {
				$list = $model->add ();
				if ($list !== false) {
					$map ['iid'] = $list;
					$datas ['code'] = 'I' . $list;
					$lists = $model->where ( $map )->save ( $datas );
					$this->redirect ( 'Image/upload', array ('success' => 2 ) );
				} else {
					$picurl = explode ( ',', $_POST ['url'] );
					$num = count ( $picurl );
					for($i = 0; $i < $num; $i ++) {
						unlink ( './Public/Uploads/Image/' . $picurl [$i] );
						unlink ( './Public/Uploads/Image/m_' . $picurl [$i] );
						unlink ( './Public/Uploads/Image/s_' . $picurl [$i] );
						unlink ( './Public/Uploads/Image/sy_' . $picurl [$i] );
					}
					$this->redirect ( 'Image/upload', array ('success' => 1, 'error' => $model->getError () ) );
				}
			} else {
				$picurl = explode ( ',', $_POST ['url'] );
				$num = count ( $picurl );
				for($i = 0; $i < $num; $i ++) {
					unlink ( './Public/Uploads/Image/' . $picurl [$i] );
					unlink ( './Public/Uploads/Image/m_' . $picurl [$i] );
					unlink ( './Public/Uploads/Image/s_' . $picurl [$i] );
					unlink ( './Public/Uploads/Image/sy_' . $picurl [$i] );
				}
				$this->redirect ( 'Image/upload', array ('success' => 1, 'error' => $model->getError () ) );
			}
		}
	}
	//挂图三级页面
	public function info() {
		
		if ($_GET ['vid']) {
			//echo "this is a three grade";
			$pic = M ( 'Image' );
			
			$user = M ( 'User' );
			
			$map ['iid'] = $_GET ['vid'];
			$iid=$_GET ['vid'];
			$info = $pic->where ( $map )->find ();
			if(($info['is_dele']==1)||($info['status'])==0)
			{
				$this->error("此资源已被删除,或未通过审核!");
			}
			$maps ['uid'] = $info ['uid'];
			$uinfo = $user->field ( 'nickname' )->where ( $maps )->find ();
			$info ['nickname'] = $uinfo ['nickname'];
			$url = explode ( ',', $info ['url'] );
			$size = explode ( ',', $info ['size'] );
			$area = explode ( ',', $info ['area'] );
			$info['size']=$size;
			$info['sizecount']=count($size);
			$info['area']=$area;
			$info['areacount']=count($area);
			
			foreach($url as $ky => $vl){
				if(file_exists('./Public/Uploads/Image/sy_'.$vl)){
					$url1[$ky]['sy'] = "sy_".$vl;
				}else{
					$url1[$ky]['sy'] = "s_".$vl;
				}
				$url1[$ky]['url'] = $vl;
			}
			
			$this->assign('counturl',count($url));
			$this->assign ( 'url', $url1 );
			$this->assign ( 'size', $size );
			$this->assign ( 'area', $area );
			$this->assign ( 'info', $info );
			$mps ['is_dele'] = 0;
			$mps ['status'] = 1;
			$hotlist = $pic->field ( 'pid,title,url' )->where ( $mps )->order ( 'point desc' )->limit ( '4' )->select ();
			foreach ( $hotlist as $key => $val ) {
				$hotlist [$key] ['url'] = explode ( ',', $val ['url'] );
			}
			$mps ['cateid'] = $uinfo ['cateid'];
			$xglist = $pic->field ( 'pid,title,url' )->where ( $mps )->limit ( '4' )->select ();
			foreach ( $xglist as $keys => $vals ) {
				$xglist [$keys] ['url'] = explode ( ',', $vals ['url'] );
			}
			$this->assign ( 'hotlist', $hotlist );
			$this->assign ( 'xglist', $xglist );
			if (strtolower ( $_SERVER ['REQUEST_METHOD'] ) == 'post') {
			
			}
			//获取相关挂图
			$dap['status']=1;
			$dap['is_dele']=0;
			$dap['cateid']=$info['cateid'];
			$dap['iid']  = array('NEQ',$iid);
			$keyword=explode('|', $info['keyword']);
			for($m=0;$m<count($keyword);$m++)
			{
				if($m!=count($keyword)-1)
				{
					$liketitle .= ' (title like \'%'.$keyword[$m].'%\')  OR ' ;
				}
				else 
				{
					$liketitle .= ' (title like \'%'.$keyword[$m].'%\')   ' ;
				}
			}
			$dap['_string']=$liketitle;
			$xlist=$pic->where($dap)->limit('0,4')->select();
			foreach ($xlist as $k=>$v)
			{
				$furl=explode(',', $v['url']);
				$xlist[$k]['url']=$furl[0];
				//print_r($v['url']);
			}
			if($xlist){
				$xsta = 1;
			}else{
				$xsta = 0;
			}
			$this->assign('xsta',$xsta);
			$this->assign('xlist',$xlist);	
			//获取热门挂图
			$sap['status']=1;
			$sap['is_dele']=0;
			$rlist=$pic->where($sap)->limit('0,4')->order('point desc')->select();
			foreach ($rlist as $k=>$v)
			{
				$furl=explode(',', $v['url']);
				$rlist[$k]['url']=$furl[0];
			}
			if($rlist){
				$rsta = 1;
			}else{
				$rsta = 0;
			}
			$this->assign('rsta',$rsta);
			$this->assign('rlist',$rlist);		
			//获取资源评论
			import("ORG.Util.Page");
			$comment = M ( 'Comment' );
			$user = M ( 'User' );
			$mapsx ['comtype'] = 6;
			$mapsx ['comstatus'] = 0;
			$mapsx ['commid'] = $_GET ['vid'];
			$pgnum = 5;
			if(strtolower($_SERVER['REQUEST_METHOD']) == 'post'){
				if($_POST['pgnum']){
					$pgnum = $_POST['pgnum'];
				}
			}
			$count = $comment->where($mapsx)->count();
			$page_com = new Page($count,$pgnum);
			
			
			$list = $comment->where($mapsx)->limit($page_com->firstRow.",".$page_com->listRows)->order('comtime desc')->select();
			//var_dump($comment->getLastSql());
			//exit;
			foreach($list as $key => $val){
				$mapss['uid'] = $val['comuid'];
				$userinfo = $user->field('nickname,image')->where($mapss)->find();
				$list[$key]['nickname'] = $userinfo['nickname'];
				if($userinfo['image']){
					$list[$key]['image'] = $userinfo['image'];
				}else{
					$list[$key]['image'] = "per_img.jpg";
				}
			}
			$this->assign("page_com",$page_com->show());
			$this->assign("count",$count);
			
			$score = getUserInfo ( 'score', false );
			$this->assign ( 'prescore', $score );
			$this->assign ( 'list', $list );
			//获取当前位置
			$hap['cateid']=$info['cateid'];
			$catefory_model=M('Category');
			$catefory=$catefory_model->where($hap)->find();
			$cate=$catefory['catename'];
			if($catefory['catepid']!=6)
			{
				$rap['cateid']=$catefory['catepid'];
				$erjicate=$catefory_model->where($rap)->find();
				$erjicatename=$erjicate['catename'];
			}
			$this->assign("erjicate",$erjicatename);
			$this->assign("erjicateid",$catefory['catepid']);
			$this->assign("cate",$cate);
			
			 //获取当前积分 
			if(session(C('USER_AUTH_KEY')) || session(C('ADMIN_AUTH_KEY')))
			{	
			$uid=getUserInfo('uid',false);
		   //$uid=getUserInfo('uid');
		   $found=M('User')->where("`uid`=$uid")->field('score')->find();
		   $score=$found['score'];
	       $this->assign('prescore',$score);
			}
			$this->display ();
		} else {
		
		}
	}
	
	//验证码
	public function verify() {
		import ( "ORG.Util.Image" );
		Image::buildImageVerify ();
	}
	//显示资源库下的分类
	

	public function showsid() {
		if (! session ( C ( 'USER_AUTH_KEY' ) ) && ! session ( C ( 'ADMIN_AUTH_KEY' ) ))
			$this->redirect ( 'User/login' );
		$pid = $_POST ['pid'];
		if ($pid) {
			$map ['catepid'] = $pid;
			$map['status'] = 1;
			$resl = M ( 'Category' )->where ( $map )->select ();
			if ($resl) {
				$res = "<option value='0' selected >选择分类</option>";
				foreach ( $resl as $key => $value ) {
					$res .= "<option value='" . $value ['cateid'] . "'  name='cateid'>" . $value ['catename'] . "</option>";
				}
				$res = "<select name='cateid' id='cateid' class='cateid' style='width:145px;'>" . $res . "</select>";
				echo $res;
			} else {
				//$res = "<option value='0' selected >新建分类</option>";
				echo 0;
			}
		} else {
			echo 0;
		}
	}
	public function checkverify() {
		if (! session ( C ( 'USER_AUTH_KEY' ) ) && ! session ( C ( 'ADMIN_AUTH_KEY' ) ))
			$this->redirect ( 'User/login' );
		$val = md5 ( $_POST ['val'] );
		if ($val) {
			if ($_SESSION ['verify'] != $val)
				echo 1;
			else
				echo 0;
		}
	}
	
	/**
	 * 下载
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter 
	 **/
	public function iamgedownload(){
	if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY'))) $this->redirect('User/login');
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
  			echo "<body><script>alert('您的帐号已被禁用');history.go(-1)</script></body></html>";
  			exit;
  		 }   
	if($_POST){
	  	if($_POST['prescore']<$_POST['score'])
	  	{
	  		echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
	  		echo "<body><script>alert('下载失败,您的积分不足');history.go(-1)</script></body></html>";
	  	}
	  	else
	  	{
	  	  $count=$_POST['count'];
		  $pid=$_POST['iid'];
	      $title=$_POST['title'];
	  	  $file_dir="./Public/Uploads/Image/";
	  	  $picture=M('Image')->where("iid=$pid")->find();
	  	  $url = explode(',', $_POST['url']);
		  $file_name=$url[$count];
		  $score='-'.$_POST['score'];
		  $addscore=$_POST['score'];
		  $code=$_POST['code'];
		  $this->assign('prescore',$_POST['prescore']);
		  $reason="下载'".$title."'";
		  $addreason="'".$title."'被下载";
	      $uid=getUserInfo('uid',false);
		  $msg=M('Image')->field('uid')->find($pid);
		  $adduid=$msg['uid'];
		  $map=array('uid'=>$uid,'code'=>$code);
		  $record=M('Score')->where($map)->find();
		  if(download($file_dir,$file_name,$title))
		  {
		      M('Image')->where("iid=$pid")->setInc('point');
		      if($_POST['once']==1)
		      {
				  if(!in_array($code,$record))
				  {
					  income($uid,$score,$reason,$code);
					  income($adduid,$addscore,$addreason,$code);
		          }
		      }
		  }
		  else 
		  {
		  	  echo "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head>";
		  	echo "<body><script>alert('下载失败,暂无可下载的水印图片');history.go(-1)</script></body></html>";
		  }
	  	}
	 }
   }
   
   //发表评论
	public function fbcomment(){
		$uid=getUserInfo('uid');
   		$basic=M('User')->find($uid); 
   		if($basic['status'] == 2){
		  	if(session(C("USER_AUTH_KEY")))
			{
				if(session(C("USER_AUTH_KEY"))){
					session(C("USER_AUTH_KEY"),NULL);	
				}
				cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
				cookie(C('USER_AUTH_PWD'),null,-3600);
			}
			echo "您已被禁用！";
			exit;
  		 }
		
		if(getUserInfo('uid')){
			$cond = $_POST;
			$cond['comuid'] = getUserInfo('uid');
			$cond['_column'] = array('comtype','comcontent','commid','commname','comuid');
			foreach ($cond['_column'] as $one) $data[$one] = trim($cond[$one]);
			$model = D('Comment');
			if($model->create($data))
			{
				if(($comid = $model->add())!= false){
					echo "评论成功，审核通过后可显示。";
				}else{
					echo "评论失败";
				}
			}else{
				echo $model->getError();
			}
		}else{
			echo "登录后才能发表评论";
		}
	} 
	
	/**
	 * 收藏
	 * @author 沈威
	 * @tel 15005164276
	 * @email 403382132@qq.com
	 * Enter description here ...
	 */
	public function favorite()
	{
		
		if(!session(C('USER_AUTH_KEY')) && !session(C('ADMIN_AUTH_KEY')))
		{
			echo '请先登录!';
		}
		else 
		{
			$uid=getUserInfo('uid');
	   		$basic=M('User')->find($uid); 
	   		if($basic['status'] == 2){
			  	if(session(C("USER_AUTH_KEY")))
				{
					if(session(C("USER_AUTH_KEY"))){
						session(C("USER_AUTH_KEY"),NULL);	
					}
					cookie(C('USER_AUTH_ACCOUNT'),null,-3600);
					cookie(C('USER_AUTH_PWD'),null,-3600);
				}
				echo "您已被禁用！";
				exit;
	  		 }
			
			$type=$_POST['type'];
			$vid=$_POST['vid'];
			$name=$_POST['name'];
			$favoritemodel=M('Favorite');
			$uid=getUserInfo('uid',false);
			$data['uid']=$uid;
			$data['fatype']=$type;
			$data['favid']=$vid;
			$data['favname']=$name;
			$favoritemodel->add($data);
			echo "已收藏！";
			//echo $favoritemodel->getLastSql();
		}
	}
}